package com.atguigu.gmall.product.service.impl;


import com.atguigu.gmall.model.product.BaseAttrInfo;
import com.atguigu.gmall.model.product.BaseAttrValue;
import com.atguigu.gmall.product.mapper.BaseAttrInfoMapper;
import com.atguigu.gmall.product.mapper.BaseAttrValueMapper;
import com.atguigu.gmall.product.service.BaseAttrInfoService;
import com.atguigu.gmall.product.service.BaseAttrValueService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
* @author h8467
* @description 针对表【base_attr_info(属性表)】的数据库操作Service实现
* @createDate 2022-11-01 14:01:54
*/
@Service
public class BaseAttrInfoServiceImpl extends ServiceImpl<BaseAttrInfoMapper, BaseAttrInfo>
    implements BaseAttrInfoService {

    @Autowired
    BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    BaseAttrValueService baseAttrValueService;
    @Override
    public List<BaseAttrInfo> getAttrInfoByCategoryId (Long c1id, Long c2id, Long c3id) {
        List attrInfoByCategoryId = baseAttrInfoMapper.getAttrInfoByCategoryId (c1id, c2id, c3id);
        return attrInfoByCategoryId;
    }

    @Override
    public void deleteAadSaveAndUpdateBaseAttrInfoByBaseAttrInfo (BaseAttrInfo baseAttrInfo) {
        deleteBaseAttrInfoById (baseAttrInfo);
        saveAndUpdateBaseAttrInfo (baseAttrInfo);
    }

    /**
     * 删除 AttrInfo内的内容
     * @param baseAttrInfo
     */
    private void deleteBaseAttrInfoById (BaseAttrInfo baseAttrInfo) {
        QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<> ();
        ArrayList<Long> ids = new ArrayList<> ();
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList ();
        for (BaseAttrValue baseAttrValue : attrValueList) {
            if (baseAttrValue.getId ()!=null){
                ids.add (baseAttrValue.getId ());
            }
        }
        if (ids.size ()>0){
            queryWrapper.notIn ("id",ids);
        }
        queryWrapper.eq ("attr_id", baseAttrInfo.getId ());
        baseAttrValueMapper.delete (queryWrapper);
    }

    /**
     * 新建or修改AttrInfo的内容
     * @param baseAttrInfo
     */
    private void saveAndUpdateBaseAttrInfo (BaseAttrInfo baseAttrInfo) {
        this.saveOrUpdate (baseAttrInfo);
        Long id = baseAttrInfo.getId ();
        if (baseAttrInfo.getAttrValueList ()!=null){
            List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList ();
            for (BaseAttrValue baseAttrValue : attrValueList) {
                baseAttrValue.setAttrId (id);
                baseAttrValueService.saveOrUpdate (baseAttrValue);
            }
        }
    }


}




